package com.ruoyi.common.utils.poi;

import cn.hutool.core.util.StrUtil;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import java.util.List;
import java.util.Map;

/**
 * 表格处理Util
 */
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class XWPFDocumentUtil {
    /**
     * 循环填充表格内容
     */
    public static void insertValueToTable(XWPFDocument xwpfDocument, List<Map<String, String>> params, int tableIndex, int startRow)
            throws Exception {
        List<XWPFTable> tableList = xwpfDocument.getTables();
        if (tableList.size() <= tableIndex) {
            throw new Exception("tableIndex对应的表格不存在");
        }
        XWPFTable table = tableList.get(tableIndex);
        List<XWPFTableRow> rows = table.getRows();
        if (rows.size() < 2) {
            throw new Exception("tableIndex对应表格应该为2行");
        }
        //模板的那一行
        XWPFTableRow tmpRow = rows.get(startRow);


        Map<String, Object> totalMap = null;
        int rowIndex = startRow;
        for (int i = 0, len = params.size(); i < len; i++) {
            Map<String, String> map = params.get(i);
            rowIndex++;
            addRow(map, table, tmpRow, rowIndex, startRow);
        }
        // 删除模版行
        table.removeRow(startRow);
    }

    /**
     * 循环填充表格内容
     */
    private static void addRow(Map<String, String> map, XWPFTable table, XWPFTableRow tmpRow, int rowIndex, int templateRowIndex) throws Exception {
        List<XWPFTableCell> tmpCells = tmpRow.getTableCells();
        // 创建新的一行
        XWPFTableRow row = createRow(table, rowIndex, templateRowIndex);
        // 获取模板的行高 设置为新一行的行高
        row.setHeight(tmpRow.getHeight());
        List<XWPFTableCell> cells = row.getTableCells();
        for (int k = 0, klen = cells.size(); k < klen; k++) {
            XWPFTableCell tmpCell = tmpCells.get(k);
            XWPFTableCell cell = cells.get(k);
            System.out.println(cell.getText());
            String cellText = tmpCell.getText();
            if (StrUtil.isNotBlank(cellText)) {
                //转换为mapkey对应的字段
                String cellTextKey = cellText.replace("$", "").replace("{", "").replace("}", "");
                if (map.containsKey(cellTextKey)) {
                    // 填充内容 并且复制模板行的属性
                    for (int j = 0; j < cell.getParagraphs().size(); j++) {
                        cell.removeParagraph(j);
                    }
                    cell.setText("");
                    setCellText(tmpCell, cell, map.get(cellTextKey));
                }
            }
        }

        table.addRow(row, rowIndex);
    }

    // 创建新的一行
    public static XWPFTableRow createRow(XWPFTable table, int rowIndex, int templateRowIndex) {
        CTTbl ctTbl = table.getCTTbl();
        CTRow templateRow = ctTbl.getTrArray(templateRowIndex);
        CTRow newRow = (CTRow) templateRow.copy();

        XWPFTableRow tabRow = new XWPFTableRow(newRow, table);

        return tabRow;
    }

    /**
     * 复制模板行的属性
     */
    private static void setCellText(XWPFTableCell tmpCell, XWPFTableCell cell, String text) throws Exception {
        CTTc cttc2 = tmpCell.getCTTc();
        CTTcPr ctPr2 = cttc2.getTcPr();
        CTTc cttc = cell.getCTTc();
        CTTcPr ctPr = cttc.addNewTcPr();
        if (ctPr2.getTcW() != null) {
            ctPr.addNewTcW().setW(ctPr2.getTcW().getW());
        }
        if (ctPr2.getVAlign() != null) {
            ctPr.addNewVAlign().setVal(ctPr2.getVAlign().getVal());
        }
        if (cttc2.getPList().size() > 0) {
            CTP ctp = cttc2.getPList().get(0);
            if (ctp.getPPr() != null) {
                if (ctp.getPPr().getJc() != null) {
                    cttc.getPList().get(0).addNewPPr().addNewJc()
                            .setVal(ctp.getPPr().getJc().getVal());
                }
            }
        }
        if (ctPr2.getTcBorders() != null) {
            ctPr.setTcBorders(ctPr2.getTcBorders());
        }

        XWPFParagraph tmpP = tmpCell.getParagraphs().get(0);
        XWPFParagraph cellP = cell.getParagraphs().get(0);
        XWPFRun tmpR = null;
        if (tmpP.getRuns() != null && tmpP.getRuns().size() > 0) {
            tmpR = tmpP.getRuns().get(0);
        }
        XWPFRun cellR = cellP.createRun();
        cellR.setText(text);
        // 复制字体信息
        copyFont(tmpR, cellR);
        // 复制段落信息
        copyParagraph(cellP, tmpP);
    }

    /**
     * 复制段落信息
     */
    private static void copyParagraph(XWPFParagraph cellP, XWPFParagraph tmpP) {
        cellP.setAlignment(tmpP.getAlignment());
        cellP.setVerticalAlignment(tmpP.getVerticalAlignment());
        cellP.setBorderBetween(tmpP.getBorderBetween());
        cellP.setBorderBottom(tmpP.getBorderBottom());
        cellP.setBorderLeft(tmpP.getBorderLeft());
        cellP.setBorderRight(tmpP.getBorderRight());
        cellP.setBorderTop(tmpP.getBorderTop());
        cellP.setPageBreak(tmpP.isPageBreak());
        if (tmpP.getCTP() != null) {
            if (tmpP.getCTP().getPPr() != null) {
                CTPPr tmpPPr = tmpP.getCTP().getPPr();
                CTPPr cellPPr = cellP.getCTP().getPPr() != null ? cellP
                        .getCTP().getPPr() : cellP.getCTP().addNewPPr();
                // 复制段落间距信息
                copyParagraphSpacingInformation(tmpPPr, cellPPr);
                // 复制段落缩进信息
                copyInd(tmpPPr, cellPPr);
            }
        }
    }

    /**
     * 复制字体信息
     */
    private static void copyFont(XWPFRun tmpR, XWPFRun cellR) {
        if (tmpR == null) {
            return;
        }
        if (!cellR.isBold()) {
            cellR.setBold(tmpR.isBold());
        }
        cellR.setItalic(tmpR.isItalic());
        cellR.setUnderline(tmpR.getUnderline());
        cellR.setColor(tmpR.getColor());
        cellR.setTextPosition(tmpR.getTextPosition());
        if (tmpR.getFontSize() != -1) {
            cellR.setFontSize(tmpR.getFontSize());
        }
        if (tmpR.getFontFamily() != null) {
            cellR.setFontFamily(tmpR.getFontFamily());
        }
        if (tmpR.getCTR() == null) {
            return;
        }
        if (!tmpR.getCTR().isSetRPr()) {
            return;
        }
        CTRPr tmpRPr = tmpR.getCTR().getRPr();
        if (tmpRPr.getRFontsArray().length == 0) {
            CTFonts tmpFonts = tmpRPr.getRFontsArray(0);
            CTRPr cellRPr = cellR.getCTR().isSetRPr() ? cellR
                    .getCTR().getRPr() : cellR.getCTR().addNewRPr();
            CTFonts cellFonts = cellRPr.getRFontsArray().length > 0 ? cellRPr
                    .getRFontsArray(0) : cellRPr.addNewRFonts();
            cellFonts.setAscii(tmpFonts.getAscii());
            cellFonts.setAsciiTheme(tmpFonts.getAsciiTheme());
            cellFonts.setCs(tmpFonts.getCs());
            cellFonts.setCstheme(tmpFonts.getCstheme());
            cellFonts.setEastAsia(tmpFonts.getEastAsia());
            cellFonts.setEastAsiaTheme(tmpFonts.getEastAsiaTheme());
            cellFonts.setHAnsi(tmpFonts.getHAnsi());
            cellFonts.setHAnsiTheme(tmpFonts.getHAnsiTheme());
        }
    }

    /**
     * 复制段落间距信息
     */
    public static void copyParagraphSpacingInformation(CTPPr tmpPPr, CTPPr cellPPr) {
        CTSpacing tmpSpacing = tmpPPr.getSpacing();
        if (tmpSpacing != null) {
            CTSpacing cellSpacing = cellPPr.getSpacing() != null ? cellPPr
                    .getSpacing() : cellPPr.addNewSpacing();
            if (tmpSpacing.getAfter() != null) {
                cellSpacing.setAfter(tmpSpacing.getAfter());
            }
            if (tmpSpacing.getAfterAutospacing() != null) {
                cellSpacing.setAfterAutospacing(tmpSpacing
                        .getAfterAutospacing());
            }
            if (tmpSpacing.getAfterLines() != null) {
                cellSpacing.setAfterLines(tmpSpacing.getAfterLines());
            }
            if (tmpSpacing.getBefore() != null) {
                cellSpacing.setBefore(tmpSpacing.getBefore());
            }
            if (tmpSpacing.getBeforeAutospacing() != null) {
                cellSpacing.setBeforeAutospacing(tmpSpacing
                        .getBeforeAutospacing());
            }
            if (tmpSpacing.getBeforeLines() != null) {
                cellSpacing.setBeforeLines(tmpSpacing.getBeforeLines());
            }
            if (tmpSpacing.getLine() != null) {
                cellSpacing.setLine(tmpSpacing.getLine());
            }
            if (tmpSpacing.getLineRule() != null) {
                cellSpacing.setLineRule(tmpSpacing.getLineRule());
            }
        }
    }

    /**
     * 复制段落缩进信息
     */
    public static void copyInd(CTPPr tmpPPr, CTPPr cellPPr) {
        CTInd tmpInd = tmpPPr.getInd();
        if (tmpInd != null) {
            CTInd cellInd = cellPPr.getInd() != null ? cellPPr.getInd()
                    : cellPPr.addNewInd();
            if (tmpInd.getFirstLine() != null) {
                cellInd.setFirstLine(tmpInd.getFirstLine());
            }
            if (tmpInd.getFirstLineChars() != null) {
                cellInd.setFirstLineChars(tmpInd.getFirstLineChars());
            }
            if (tmpInd.getHanging() != null) {
                cellInd.setHanging(tmpInd.getHanging());
            }
            if (tmpInd.getHangingChars() != null) {
                cellInd.setHangingChars(tmpInd.getHangingChars());
            }
            if (tmpInd.getLeft() != null) {
                cellInd.setLeft(tmpInd.getLeft());
            }
            if (tmpInd.getLeftChars() != null) {
                cellInd.setLeftChars(tmpInd.getLeftChars());
            }
            if (tmpInd.getRight() != null) {
                cellInd.setRight(tmpInd.getRight());
            }
            if (tmpInd.getRightChars() != null) {
                cellInd.setRightChars(tmpInd.getRightChars());
            }
        }
    }
}
